import { BehaviorSubject } from 'rxjs';
import { singleton, container } from 'src/common/services/di';
import { LocalStorageService } from 'src/common/storage/local.storage';
import { StorageScope } from 'src/common/storage/storage';

@singleton()
class WatchUserActionService {
  private _timer: any;
  private _domtimer: any;
  private _isNeedUnlock: boolean = true;
  private _isNeedUnlock$ = new BehaviorSubject(true);
  private _isDomVisible$ = new BehaviorSubject(true);
  private _isHiddenDom$ = new BehaviorSubject(false);

  constructor(
    private storageService: LocalStorageService
  ){
    this._isNeedUnlock = this.storageService.get('global.needLock', StorageScope.GLOBAL, 'true') === 'true';
    this._isNeedUnlock$.next(this._isNeedUnlock);
    document.addEventListener('mousemove', this.watchUserAction.bind(this));
    document.addEventListener('visibilitychange', this.watchDomVisibilityState.bind(this));
  };

  //监听用户动作
  private watchUserAction(): void {
    clearTimeout(this._timer);
    this._isNeedUnlock$.next(this._isNeedUnlock);
    this._timer = setTimeout(() => {
      this._isNeedUnlock = true;
      this._isNeedUnlock$.next(true);
      this.storageService.store('global.needLock', 'true', StorageScope.WORKSPACE);
    }, 1000 * 60 * 29);
  };

  //document.visibility状态改变的时候，如果切出去，超过10分钟了，就将网站的dom元素隐藏，防止无效刷新
  private watchDomVisibilityState(): void {
    clearTimeout(this._domtimer);
    const visible = document.visibilityState === 'visible';
    this._isDomVisible$.next(visible);

    if(!visible){
      this._domtimer = setTimeout(() => {
        this._isHiddenDom$.next(true);
      }, 1000 * 60 * 10);
    } else {
      this._isHiddenDom$.next(false);
    }
  };

  set isNeedUnlock(val: boolean) {
    if(val !== this._isNeedUnlock){
      this._isNeedUnlock = val;
      this._isNeedUnlock$.next(val);
      this.storageService.store('global.needLock', val+'', StorageScope.WORKSPACE);
    }
  };

  get isHiddenDom$(){
    return this._isHiddenDom$.asObservable();
  };
};

export const WatchUserActionServiceFactory = () => {
  return container.resolve(WatchUserActionService);
};